# -*- coding:utf-8 -*-
"""
    日志检测
"""
@config(alias="wtmp", enable=False)
def check_wtmp(option):
    """wtmp日志登陆分析，排查境外IP的登陆日志"""
    suspicious = False
    if 1:
        if not os.path.exists('/var/log/wtmp'): return suspicious
        p1 = Popen("who /var/log/wtmp 2>/dev/null", stdout=PIPE, shell=True)
        p2 = Popen("awk '{print $1\" \"$3\" \"$5}'", stdin=p1.stdout, stdout=PIPE, shell=True)
        wtmp_infos = p2.stdout.read().splitlines()
        for wtmp_info in wtmp_infos:
            if wtmp_info:
                wtmp_info = str(wtmp_info)
                if len(wtmp_info.split(' ')) != 3: continue
                user = wtmp_info.split(' ')[0]
                time = wtmp_info.split(' ')[1]
                ips = wtmp_info.split(' ')[2]

                if not ips or ips[0] != '(': continue
                ip = ips.replace('(', '').replace(')', '').replace('\n', '')
                if check_ip(ip):
                    save_result("wtmp登陆历史排查", "分析/var/log/wtmp 日志发现可疑境外IP使用%s登陆主机"%(ip), "m")
                    suspicious = True
        return suspicious
    else:
        return suspicious

@config(alias="utmp", enable=False)
def check_utmp(option):
    """utmp日志登陆分析，排查境外IP的登陆日志"""
    suspicious = False
    if 1:
        p1 = Popen("who 2>/dev/null", stdout=PIPE, shell=True)
        p2 = Popen("awk '{print $1\" \"$3\" \"$5}'", stdin=p1.stdout, stdout=PIPE, shell=True)
        utmp_infos = p2.stdout.read().splitlines()
        for utmp_info in utmp_infos:
            if utmp_info:
                utmp_info = str(utmp_info)
                if len(utmp_info.split(' ')) != 3: continue
                user = utmp_info.split(' ')[0]
                time = utmp_info.split(' ')[1]
                ips = utmp_info.split(' ')[2]
                if not ips or ips[0] != '(': continue
                ip = ips.replace('(', '').replace(')', '').replace('\n', '')
                if check_ip(ip):
                    save_result("utmp登陆历史排查", "分析/run/utmp 日志发现可疑境外IP使用%s登陆主机"%(ip), "m")
                    suspicious = True
        return suspicious
    else:
        return suspicious

@config(alias="lastlog", enable=False)
def check_lastlog(option):
    """lastlog日志登陆分析，排查境外IP的登陆日志"""
    suspicious = False
    if 1:
        if not os.path.exists('/var/log/lastlog'): return suspicious
        p1 = Popen("lastlog 2>/dev/null", stdout=PIPE, shell=True)
        p2 = Popen("awk '{if (NR>1){print $1\" \"$3}}'", stdin=p1.stdout, stdout=PIPE, shell=True)
        lastlogs = p2.stdout.read().splitlines()
        for lastlog in lastlogs:
            if lastlog:
                lastlog = str(lastlog)
                # if len(lastlog.split(' ', 3)) != 3: continue
                if len(lastlog.split(' ', 3)) != 2: continue # 这里分割后好像只有两个元素，所以在这里就continue，现在将其改为2
                user = lastlog.split(' ')[0].strip()
                ip = lastlog.split(' ')[1].replace(' ', '').replace('\n', '')
                if check_ip(ip):
                    save_result("lastlog登陆历史排查", "分析/var/log/lastlog 日志发现可疑境外IP使用%s登陆主机"%(ip), "m")
                    suspicious = True
        return suspicious
    else:
        return suspicious

@config(alias="sshbreak", enable=True)
def check_sshbreak(option):
    """排查secure SSH的爆破记录"""
    suspicious = False
    if 1:
        # correct_baopo_infos = SSH_Analysis(log_dir='/var/log/').correct_baopo_infos
        correct_baopo_infos = dir_file_detect(log_dir='/var/log/')
        if len(correct_baopo_infos) > 0:
            msgs = []
            for info in correct_baopo_infos:
                user = info['user']
                time = os.popen("date -d '" + info['time'] + "' '+%Y-%m-%d %H:%M:%S' 2>/dev/null").read().splitlines()[0]
                ip = info['ip']
                malice = True
                msgs.append("查看/var/log/secure日志 主机SSH被外部爆破且成功登陆，时间：%s，ip：%s，用户: %s"%(time, ip, user))
            for msg in set(msgs):
                save_result("SSH爆破检测", msg, "l")
        return suspicious
    else:
        return suspicious
